﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;

namespace LiveLinq.Internal
{
	sealed class WhereQueryResult<T> : ObservableCollectionQueryResultBase<T>
	{
		readonly Func<T, bool> _predicate;

		public WhereQueryResult(IEnumerable<T> source, Func<T, bool> predicate)
			: base(source)
		{
			_predicate = predicate;
			OnSourceReset();
		}

		protected override void OnSourceReset()
		{
			foreach (var item in _attached)
			{
				DetachItem(item);
			}
			_attached.Clear();
			Items.Clear();
			foreach (var item in _source)
			{
				if (_predicate(item))
				{
					Items.Add(item);
				}
				AttachItem(item);
			}
			OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
		}

		protected override void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			OnSourceReset();
		}
	}
}